﻿Imports System.Runtime.CompilerServices
Imports Telerik.Web.Mvc.UI

Public Module ViewComponentFactoryExtensions

    <Extension()>
    Public Function GetMultiSelectList(ByVal vdd As ViewDataDictionary, ByVal codLista As String, ByVal valueField As String, ByVal textField As String) As MultiSelectList
        Return New MultiSelectList(CType(vdd(codLista), IEnumerable), valueField, textField)
    End Function

    <Extension()>
    Public Function GetSelectList(Of T)(ByVal vdd As ViewDataDictionary(Of T), ByVal codLista As String, ByVal valueField As String, ByVal textField As String) As SelectList
        Return New SelectList(CType(vdd(codLista), IEnumerable), valueField, textField)
    End Function

    <Extension()>
    Public Function Rejilla(Of T As Class)(ByVal vcf As ViewComponentFactory, ByVal model As IEnumerable(Of T), ByVal controller As String) As Fluent.GridBuilder(Of T)
        Return vcf.Grid(Of T)(model).AddStandardFeatures(controller)
    End Function

    <Extension()>
    Public Function RejillaAutoeditable(Of T As Class)(ByVal vcf As ViewComponentFactory, ByVal controller As String) As Fluent.GridBuilder(Of T)
        Return vcf.Grid(Of T).AddStandardFeatures(controller) _
            .ToolBar(Sub(commands) commands.Insert()) _
            .Columns(Sub(columns)
                         columns.Command(Sub(commands)
                                             commands.Edit()
                                             commands.Delete()
                                         End Sub)
                     End Sub) _
           .DataBinding(Sub(dataBinding)
                            dataBinding.Ajax() _
                            .Select("_Index", controller) _
                            .Insert("_Insert", controller) _
                            .Update("_Edit", controller) _
                            .Delete("_Delete", controller)
                        End Sub) _
           .Editable(Function(gesb) gesb.Mode(GridEditMode.InLine))
    End Function

    <Extension()>
    Public Function AddStandardFeatures(Of T As Class)(ByVal gb As Fluent.GridBuilder(Of T), ByVal controller As String) As Fluent.GridBuilder(Of T)
        Return gb _
            .Name("Grid") _
            .Sortable() _
            .Pageable(Sub(paging) paging.PageSize(15)) _
            .Filterable() _
            .Footer(True)
    End Function

    <Extension()>
    Public Function DataKey(Of T As Class, TValue)(ByVal gb As Fluent.GridBuilder(Of T), ByVal expr As System.Linq.Expressions.Expression(Of Func(Of T, TValue))) As Fluent.GridBuilder(Of T)
        Return gb.DataKeys(Sub(gen) gen.Add(expr))
    End Function
End Module
